package com.carrot.uaa.web.consumer;

import cn.hutool.core.collection.CollectionUtil;
import com.carrot.uaa.entity.RedisClient;
import com.carrot.uaa.infrastructure.mapper.RegisteredClientMapper;
import com.carrot.uaa.infrastructure.redis.RedisClientRepository;
import com.carrot.uaa.infrastructure.redis.RedisOperator;
import com.carrot.uaa.util.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.List;

/**
 * 监听spring事件
 */
@Component
@AllArgsConstructor
@Slf4j
public class SpringApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    private final RegisteredClientMapper registeredClientMapper;

    private final RedisClientRepository redisClientRepository;

    private final RedisOperator<Object> redisOperator;

    @Override
    @SneakyThrows
    public void onApplicationEvent(ApplicationReadyEvent event) {
        //缓存客户端
        log.info("cache client start");
       List<RedisClient> requireCacheData = registeredClientMapper.getRequireCacheData();
        if(CollectionUtil.isNotEmpty(requireCacheData)){
            for(RedisClient redisClient:requireCacheData){
                if(redisOperator.hseKey(RedisUtils.getClientIdKey(redisClient.getClientId()))){
                    continue;
                }
                redisClientRepository.save(redisClient);
            }
        }
        log.info("cache client end");
        ConfigurableApplicationContext application = event.getApplicationContext();
        Environment env = application.getEnvironment();
        // 睡一秒打印
        Thread.sleep(1);
        log.info("\n----------------------------------------------------------\n\t" +
                        "Application '{}' is running! Access URLs:\n\t" +
                        "Local: \t\thttp://localhost:{}\n\t" +
                        "External: \thttp://{}:{}\n\t"+
                        "Doc: \thttp://{}:{}/doc.html\n"+
                        "----------------------------------------------------------",
                env.getProperty("spring.application.name"),
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"),
                InetAddress.getLocalHost().getHostAddress(),
                env.getProperty("server.port"));
    }
}
